//
//  UILabel+SLExtension.m
//  ECERP.CRM
//
//  Created by 刘思麟 on 2018/10/22.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "UILabel+SLExtension.h"

@implementation UILabel (SLExtension)

+ (void)load {
    Method method1 = class_getInstanceMethod([self class], @selector(setText:));
    Method method2 = class_getInstanceMethod([self class], @selector(sl_setText:));
    method_exchangeImplementations(method1, method2);
}

- (void)sl_setText:(NSString *)text {
    [self sl_setText:text];
    if ([objc_getAssociatedObject(self, "isLeftAndRight") boolValue]) {
        [self alignmentMethodLeftAndRight];
    }
}

- (void)setLeftAndRight {
    objc_setAssociatedObject(self, "isLeftAndRight", @(YES), OBJC_ASSOCIATION_COPY);
}

- (void)alignmentMethodLeftAndRight {
    [self layoutIfNeeded];
    if (!self.text || self.text.length < 1) {
        return;
    }
    
    NSString * str = [self.text substringWithRange:NSMakeRange(0, self.text.length)];
    
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading
                                     attributes:@{NSFontAttributeName :self.font}
                                        context:nil].size;
    //计算字间距
    CGFloat margin = (self.frame.size.width - textSize.width) / (str.length - 1);
    NSNumber *number = [NSNumber numberWithFloat:margin];
    
    //修改默认字间距离
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:str];
    [attributeString addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, str.length -1 )];
    self.attributedText = attributeString;
}

@end
